// @Author YaoYa
// @Date 2024-10-14 16:54:00
// @Desc
package initialize

import (
	"fmt"
	_ "github.com/mbobakov/grpc-consul-resolver" // It's important
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"mxshop-api/order-web/global"
	"mxshop-api/order-web/proto"
)

// InitSrvConn 使用grpc-consul-resolver初始化连接,进行负载均衡
func InitSrvConn() {
	//consul: //192.168.31.33:8500/user-srv?wait=14s&tag=srv"
	orderConn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s", global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port, global.ServerConfig.GoodsSrvInfo.Name),
		grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)

	if err != nil { //为什么服务端没有启动 err还是不为nil
		zap.S().Fatal("[InitSrvConn] 连接 【用户服务】失败",
			"msg", err.Error(),
		)
	}

	//生成grpc的client并调用接口
	global.OrderSrvClient = proto.NewOrderClient(orderConn)

	//初始化第三方微服务client
	goodsConn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s", global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port, global.ServerConfig.GoodsSrvInfo.Name),
		grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)

	if err != nil { //为什么服务端没有启动 err还是不为nil
		zap.S().Fatal("[InitSrvConn] 连接 【商品服务】失败",
			"msg", err.Error(),
		)
	}

	//生成grpc的client并调用接口
	global.GoodsSrvClient = proto.NewGoodsClient(goodsConn)

	inventoryConn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s", global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port, global.ServerConfig.InventorySrvInfo.Name),
		grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)

	if err != nil { //为什么服务端没有启动 err还是不为nil
		zap.S().Fatal("[InitSrvConn] 连接 【库存服务】失败",
			"msg", err.Error(),
		)
	}

	//生成grpc的client并调用接口
	global.InventorySrvClient = proto.NewInventoryClient(inventoryConn)

}
